package com.tanhua.appserver.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.appserver.hanlder.UserHolder;
import com.tanhua.dubbointerface.api.RecommendUserApi;
import com.tanhua.dubbointerface.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.dto.RecommendUserDto;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.TodayBest;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class TanhuaService {

    @DubboReference
    private UserInfoApi userInfoApi;
    @DubboReference
    private RecommendUserApi recommendUserApi;

    /**
     * 从mongodb中获取当前用户所对应的今日佳人的用户id
     * 通过获取的用户id访问mysql数据库获取userInfo信息并返回UserInfo对象
     * @return
     */
    public TodayBest queryWithMaxScore() {
        //获取当前用户的id
        Long toUserId = UserHolder.getUserId();
        //访问mongodb获取recommendUser对象
        RecommendUser recommendUser = recommendUserApi.queryWithMaxScore(toUserId);
        //当没找到今日佳人时，默认给一个
        if (recommendUser==null){
            recommendUser=new RecommendUser();
            recommendUser.setUserId(1l);
            recommendUser.setScore(99.0);
        }
        //获取佳人id用来访问MySQL数据库获得UserInfo对象
        Long userId = recommendUser.getUserId();
        UserInfo userInfo = userInfoApi.findUserInfoById(userId);
        //创建返回对象
        TodayBest vo = TodayBest.init(userInfo, recommendUser);
        return vo;
    }

    public PageResult recommendation(RecommendUserDto recommendUserDto) {
        //获取当前用户的id
        Long toUserId = UserHolder.getUserId();
        //2、调用recommendUserApi分页查询数据列表（PageResult -- RecommendUser）
        PageResult pr =recommendUserApi.queryRecommendUserList(recommendUserDto.getPage(),recommendUserDto.getPagesize(),toUserId);
        //3、获取分页中的RecommendUser数据列表
        List<RecommendUser> items = (List<RecommendUser>) pr.getItems();
        //4、判断列表是否为空
        if (items==null||items.size()<=0){
            return pr;
        }
        //5、提取所有推荐的用户id列表
        List<Long> ids = CollUtil.getFieldValues(items, "userId", Long.class);

        UserInfo userInfo = new UserInfo();
        userInfo.setAge(recommendUserDto.getAge());
        userInfo.setGender(recommendUserDto.getGender());
        //6、构建查询条件，批量查询所有的用户详情
        Map<Long, UserInfo> map = userInfoApi.findUserInfoByIds(ids,userInfo);
        //7、循环推荐的数据列表，构建vo对象
        List<TodayBest> list = new ArrayList<>();
        for (RecommendUser item : items) {
            UserInfo info = map.get(item.getUserId());
            if (info!=null){
                TodayBest todayBest = TodayBest.init(info,item);
                list.add(todayBest);
            }
        }
        //8、构造返回值
        pr.setItems(list);
        return pr;
    }
}
